<template>
  <div class="dashboard-container">
    <div class="header-container">
      <h5 class="panel-title">设备总览看板</h5>
      <el-input
        v-model="searchKeyword"
        placeholder="输入设备名称搜索"
        clearable
        class="search-input"
        @clear="handleSearchClear"
        @input="handleSearchInput"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </div>
    <template v-if="initialized">
      <el-table
        :data="paginatedData"
        style="width: 100%"
        header-row-class-name="custom-header"
        class="equipment-table"
      >
        <el-table-column prop="name" label="设备名称" />

        <el-table-column label="在线状态">
          <template #default="scope">
            <el-tag v-if="scope?.row?.status" :type="statusType(scope.row.status)" effect="dark">
              {{ scope.row.status }}
            </el-tag>
            <span v-else class="data-na">--</span>
          </template>
        </el-table-column>

        <el-table-column label="工作模式">
          <template #default="scope">
            <el-tag
              v-if="scope?.row?.mode"
              :type="scope.row.mode === '自动' ? undefined : 'info'"
              :color="modeColor(scope.row.mode)"
              effect="plain"
            >
              {{ scope.row.mode }}
            </el-tag>
            <span v-else class="data-na">--</span>
          </template>
        </el-table-column>

        <el-table-column label="温度报警">
          <template #default="scope">
            <div class="temperature">
              <span :class="{ 'temperature-alert': scope?.row?.tempAlert }">
                {{ scope?.row?.temperature || '--' }}
              </span>
              <el-icon v-if="scope?.row?.tempAlert" class="alert-icon">
                <Warning />
              </el-icon>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        background
        layout="prev, pager, next"
        :total="filteredData.length"
        :page-size="pageSize"
        v-model:current-page="currentPage"
        class="pagination"
      />
    </template>

    <div v-else class="loading-state">
      <el-icon class="loading-icon"><Loading /></el-icon>
      数据加载中...
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, computed, onUnmounted } from 'vue';
  import { Warning, Loading, Search } from '@element-plus/icons-vue';
  import { ElTable, ElIcon, ElTag, ElTableColumn, ElPagination, ElInput } from 'element-plus';
  import { useWebSocket } from '@vueuse/core';
  import { getEntityDeviceList } from '/src/api/thingsborad/entity/entity';
  import { useWebsocketStoreWithOut } from '/@/store/modules/thingsboard/websocket';

  interface Equipment {
    id: string;
    name: string;
    originalName?: string; // TB Gateway中的原始英文设备名
    status?: '运行中' | '待机' | '故障';
    mode?: '自动' | '手动';
    temperature?: string;
    tempAlert?: boolean;
    lastUpdated?: number;
  }

  // 添加连接状态跟踪
  const websocketReady = ref(false);
  const devicesInitialized = ref(false);

  const safeEquipmentData = ref<Equipment[]>([]);
  const pageSize = ref(3);
  const currentPage = ref(1);
  const initialized = ref(false);
  const subscriptionMap = new Map<number, string>();

  // 移除固定的设备名称映射，将从API动态获取设备

  // 新增搜索关键词响应式变量
  const searchKeyword = ref('');

  // 添加过滤后的数据计算属性
  const filteredData = computed(() => {
    return safeEquipmentData.value.filter((item) =>
      item.name.toLowerCase().includes(searchKeyword.value.toLowerCase()),
    );
  });
  // 分页数据使用深层响应
  const paginatedData = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value;
    return filteredData.value.slice(start, start + pageSize.value);
  });
  const handleSearchInput = (value: string) => {
    console.log('当前搜索关键词:', value); // 调试输出
    currentPage.value = 1; // 搜索时自动回到第一页
  };
  // 添加搜索框清除处理
  const handleSearchClear = () => {
    currentPage.value = 1; // 重置到第一页
  };
  // 获取store实例
  const websocketStore = useWebsocketStoreWithOut();

  // WebSocket 配置优化
  const { send, open, close } = useWebSocket(websocketStore.getBackendWsUrl, {
    autoReconnect: { retries: 3, delay: 5000 },
    immediate: false,
    onConnected: () => {
      websocketReady.value = true;
      console.log('WebSocket连接成功');
      // 确保设备加载完成后发送订阅
      if (devicesInitialized.value) {
        sendSubscriptionRequests();
      }
    },
    onMessage: (_, event) => handleWebSocketMessage(event.data),
  });

  // 设备初始化逻辑 - 获取设备配置为Device类型且关联特定方案的设备
  const initializeDevices = async () => {
    try {
      // 使用提供的设备配置ID获取所有关联的Device类型设备
      const deviceProfileId = '72154320-638d-11f0-baf1-1f027592f510';

      const response = await getEntityDeviceList({
        page: 0,
        pageSize: 100, // 获取足够多的设备
        deviceProfileId: deviceProfileId, // 按设备配置过滤
        // 移除active限制，获取所有设备（包括非活跃设备）
      });

      console.log('API响应数据:', response);

      // 过滤出设备配置为Device类型的设备
      const deviceList =
        response.data?.filter((device: any) => {
          return (
            device.deviceData?.configuration?.type === 'DEFAULT' ||
            device.deviceProfileId?.id === deviceProfileId
          );
        }) || [];

      safeEquipmentData.value = deviceList.map((device: any) => ({
        id: device.id.id, // 使用设备的实际ID
        name: device.name, // 使用设备的实际名称
        originalName: device.name, // 保存原始名称用于调试
        status: '待机',
        mode: '自动',
        temperature: '--',
        tempAlert: false,
        lastUpdated: Date.now(),
      }));

      devicesInitialized.value = true;
      initialized.value = true;
      console.log('设备初始化完成，数量:', safeEquipmentData.value.length);
      console.log('初始化设备列表:', safeEquipmentData.value);

      if (websocketReady.value) {
        sendSubscriptionRequests();
      }
    } catch (error) {
      console.error('设备初始化失败:', error);
      // 如果API调用失败，显示错误信息但不阻塞界面
      initialized.value = true;
    }
  };

  // 订阅方法
  const sendSubscriptionRequests = () => {
    // 生成连续cmdId（从1开始）
    let cmdIdCounter = 1;

    // 分时发送控制参数
    const INTERVAL_MS = 100; // 每个请求间隔100ms
    const BATCH_SIZE = 5;

    // 创建设备队列副本避免响应式干扰
    const deviceQueue = [...safeEquipmentData.value];

    // 分批次发送
    const sendBatch = () => {
      if (deviceQueue.length === 0) return;

      const batch = deviceQueue.splice(0, BATCH_SIZE);

      batch.forEach((device) => {
        const currentCmdId = cmdIdCounter; // 保存当前cmdId
        const subscribeRequest = {
          tsSubCmds: [
            {
              cmdId: currentCmdId,
              entityId: device.id,
              entityType: 'DEVICE',
              scope: 'LATEST_TELEMETRY',
            },
          ],
        };
        subscriptionMap.set(cmdIdCounter, device.id);
        cmdIdCounter++; // 递增计数器
        send(JSON.stringify(subscribeRequest));
        // console.log('已发送设备订阅:', device.id, subscribeRequest);
      });

      // 安排下一批次
      if (deviceQueue.length > 0) {
        setTimeout(sendBatch, INTERVAL_MS);
      }
    };

    // 启动首轮发送
    setTimeout(sendBatch, INTERVAL_MS);
  };

  // 消息处理优化
  const handleWebSocketMessage = (rawData: string) => {
    try {
      const parsedData = JSON.parse(rawData);
      // 增强条件判断
      const isValidMessage =
        parsedData.hasOwnProperty('subscriptionId') &&
        parsedData.hasOwnProperty('data') &&
        Object.keys(parsedData.data).length > 0;

      if (!isValidMessage) {
        // console.warn('忽略系统消息或空数据', parsedData);
        return;
      }
      const deviceId = subscriptionMap.get(parsedData.subscriptionId);
      if (!deviceId) {
        // console.warn('未知subscriptionId:', parsedData.subscriptionId);
        return;
      }

      const deviceIndex = safeEquipmentData.value.findIndex((d) => d.id === deviceId);

      if (deviceIndex === -1) {
        // console.warn('未知设备:', parsedData.entityId);
        return;
      }

      // 深拷贝创建新对象
      const updatedDevice = JSON.parse(JSON.stringify(safeEquipmentData.value[deviceIndex]));

      Object.entries(parsedData.data).forEach(([key, values]) => {
        if (!Array.isArray(values) || values.length === 0) return;

        const [timestamp, value] = values[0];
        console.log(`设备[${updatedDevice.name}] 字段更新:`, {
          field: key,
          value,
          type: typeof value,
          timestamp,
          deviceId,
        });

        // 统一小写处理字段名
        const field = key.toLowerCase();

        // 类型安全转换
        const strValue = String(value).toLowerCase();
        const numValue = Number(value);

        switch (field) {
          case 'status':
            // 处理16int数值类型的状态
            if (typeof numValue === 'number' && !isNaN(numValue)) {
              switch (numValue) {
                case 0:
                  updatedDevice.status = '待机';
                  break;
                case 1:
                  updatedDevice.status = '运行中';
                  break;
                case 2:
                  updatedDevice.status = '故障';
                  break;
                default:
                  updatedDevice.status = '未知';
              }
            } else {
              // 兼容字符串格式
              updatedDevice.status =
                strValue === 'active' || strValue === 'running'
                  ? '运行中'
                  : strValue === 'standby'
                  ? '待机'
                  : strValue === 'fault'
                  ? '故障'
                  : '未知';
            }
            break;

          case 'mode':
            // 处理16int数值类型的模式
            if (typeof numValue === 'number' && !isNaN(numValue)) {
              updatedDevice.mode = numValue === 1 ? '自动' : '手动';
            } else {
              // 兼容字符串格式
              updatedDevice.mode = strValue === 'auto' ? '自动' : '手动';
            }
            break;

          case 'temperature':
            // 处理16int数值类型的温度
            if (typeof numValue === 'number' && !isNaN(numValue)) {
              // 直接使用数值，添加单位
              updatedDevice.temperature = `${numValue}℃`;
              // 温度报警逻辑
              updatedDevice.tempAlert = numValue > 50 || numValue < 0;
            } else {
              updatedDevice.temperature = parseTemperature(value);
            }
            break;

          case 'tempalert':
          case 'temp_alert':
            if (typeof numValue === 'number' && !isNaN(numValue)) {
              updatedDevice.tempAlert = numValue === 1;
            } else {
              updatedDevice.tempAlert = String(value).toLowerCase() === 'true';
            }
            break;
        }
      });

      // 触发响应式更新
      safeEquipmentData.value.splice(deviceIndex, 1, updatedDevice);

      // console.log('设备更新完成:', updatedDevice);
    } catch (error) {
      console.error('消息处理失败:', error);
    }
  };

  const parseTemperature = (value: any) => {
    const num = parseFloat(String(value).replace(/[^0-9.-]/g, ''));
    return isNaN(num) ? '--' : `${num.toFixed(1)}℃`;
  };
  // 显示相关保持不变
  const statusType = (status?: string): 'success' | 'warning' | 'danger' | 'info' => {
    const typeMap: Record<string, 'success' | 'warning' | 'danger' | 'info'> = {
      运行中: 'success',
      待机: 'warning',
      故障: 'danger',
    };
    return typeMap[status?.trim() ?? ''] || 'info';
  };
  const modeColor = (mode?: string) => (mode === '自动' ? '#409eff' : '#909399');

  // 修改onMounted部分
  const isMounted = ref(false);
  onMounted(async () => {
    if (isMounted.value) return;
    isMounted.value = true;

    await initializeDevices();
    open();
  });

  onUnmounted(() => {
    close();
  });
</script>

<style scoped>
  .dashboard-container {
    background: rgba(255, 255, 255, 0.1); /* 透明蒙版效果 */
    padding: 1vw;
    height: 40vh;
  }
  .panel-title {
    margin: 0 0 1vw 0;
    font-size: 1vw;
    color: white;
  }

  .header-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    position: relative;
    z-index: 1;
  }
  .search-input {
    width: 8vw;
    height: 3vh;
    background: rgba(255, 255, 255, 0.1);
    border-radius: 4px;
    transition: all 0.3s;
  }
  /* 修复输入框内部样式 */
  :deep(.search-input .el-input__wrapper) {
    background: transparent !important;
    box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.3) !important;
  }

  :deep(.search-input .el-input__inner) {
    color: rgba(255, 255, 255, 0.8) !important;
  }

  :deep(.search-input .el-icon) {
    color: rgba(255, 255, 255, 0.6) !important;
    margin-right: 8px;
  }
  .pagination {
    margin-top: 15px;
    justify-content: center;
  }
  /* 分页器深度样式定制 */
  :deep(.el-pagination) {
    --el-pagination-bg-color: transparent;
    --el-pagination-button-disabled-bg-color: transparent;
    --el-pagination-button-bg-color: rgba(255, 255, 255, 0.08);
    --el-pagination-button-color: rgba(255, 255, 255, 0.8);
    --el-pagination-button-hover-color: #409eff;
  }

  /* 分页项通用样式 */
  :deep(.el-pagination .btn-prev),
  :deep(.el-pagination .btn-next),
  :deep(.el-pagination .number) {
    background: rgba(255, 255, 255, 0.08) !important;
    border: 1px solid rgba(255, 255, 255, 0.1);
    border-radius: 4px;
    margin: 0 4px;
    min-width: 32px;
    height: 32px;
    transition: all 0.3s ease;
  }

  /* 当前页突出显示 */
  :deep(.el-pagination .is-active) {
    background: #409eff !important;
    border-color: #409eff;
    color: white !important;
    font-weight: 500;
  }

  /* 悬停效果 */
  :deep(.el-pagination li:not(.is-active):hover) {
    background: rgba(255, 255, 255, 0.15) !important;
    border-color: rgba(255, 255, 255, 0.3);
    color: #409eff !important;
  }

  /* 禁用状态 */
  :deep(.el-pagination button:disabled) {
    opacity: 0.5;
    background: rgba(255, 255, 255, 0.05) !important;
  }

  /* 页码输入框样式 */
  :deep(.el-pagination__jump) {
    color: rgba(255, 255, 255, 0.8);
  }
  :deep(.el-pagination__editor) {
    background: rgba(255, 255, 255, 0.08);
    border-color: rgba(255, 255, 255, 0.2);
    color: white;
  }
  /* 表格样式 */
  :deep(.equipment-table) {
    --el-table-border-color: rgba(255, 255, 255, 0.1); /* 浅灰色表格线 */
    --el-table-text-color: rgba(255, 255, 255, 0.9);
    --el-table-header-text-color: rgba(255, 255, 255, 0.8);
    --el-table-row-hover-bg-color: rgba(255, 255, 255, 0.05);
    --el-tag-text-color: white !important;
    background: transparent;
    --el-table-tr-bg-color: transparent;
    font-size: 0.8vw;
    height: 24vh;
  }
  :deep(.el-tag) {
    --el-tag-text-color: white !important;
  }
  :deep(.el-table th) {
    background: rgba(255, 255, 255, 0.08) !important;
  }

  :deep(.el-table td) {
    background: transparent !important;
    border-bottom: 0.2vh solid var(--el-table-border-color);
  }

  .temperature {
    display: flex;
    align-items: center;
    gap: 6px;
  }

  .temperature-alert {
    color: #f56c6c;
    font-weight: 500;
  }

  .alert-icon {
    color: #f56c6c;
    font-size: 1vw;
  }

  /* 加载状态 */
  .loading-state {
    color: rgba(255, 255, 255, 0.8);
  }
</style>
